package com.gnrsoft.springboot_test.commons.http;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * HttpClient配置类
 *
 */
@Configuration
public class HttpClientConfig {

	@Value("${http.maxTotal}")
	private Integer maxTotal;

	@Value("${http.defaultMaxPerRoute}")
	private Integer defaultMaxPerRoute;

	@Value("${http.connectTimeOut}")
	private Integer connectTimeOut;

	@Value("${http.connectionRequestTimeout}")
	private Integer connectionRequestTimeout;

	@Value("${http.socketTimeout}")
	private Integer socketTimeout;

//	private boolean staleConnectionCheckEnabled;

	/**
	 * 实例化连接池管理器  ，设置最大连接数，并发连接数
	 * @return
	 */
	@Bean
	public PoolingHttpClientConnectionManager getHttpClientConnectionManager() {
		PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager();
		httpClientConnectionManager.setMaxTotal(maxTotal);
		httpClientConnectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
		return httpClientConnectionManager;
	}
	/**
	 * 实例化连接池，设置连接池管理器
	 * @param httpClientConnectionManager
	 * @return
	 */
	@Bean
	public HttpClientBuilder getHttpClientBuilder(PoolingHttpClientConnectionManager httpClientConnectionManager) {
		HttpClientBuilder clientBuilder = HttpClientBuilder.create();
		clientBuilder.setConnectionManager(httpClientConnectionManager);
		return clientBuilder;
	}

	/**
	 * 注入连接池，用于获取http
	 * @param httpClientBuilder
	 * @return
	 */
	@Bean
	public CloseableHttpClient getCloseableHttpClient(HttpClientBuilder httpClientBuilder) {
		return httpClientBuilder.build();
	}
	
	/**
	 * Builder 是 RequestConfig内部类
	 * 通过 RequestConfig.custom获取 Builder实例 
	 * 设置 Builder的连接信息
	 * 可以设置 proxy cookieSpec等属性
	 * @return
	 */
	@Bean
	public Builder getBuilder() {
		Builder builder = RequestConfig.custom();
		return builder.setConnectTimeout(connectTimeOut).setConnectionRequestTimeout(connectionRequestTimeout)
				.setSocketTimeout(socketTimeout).setSocketTimeout(socketTimeout);
//				.setStaleConnectionCheckEnabled(staleConnectionCheckEnabled);
	}
	
	/**
	 * 使用 Builder 构建一个RequestConfig 对象
	 * @param builder
	 * @return
	 */
	@Bean
	public RequestConfig getRequestConfig(Builder builder){
		return builder.build();
	}

}
